package com.igd.socket.sdk.nio.multi_reactor;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

import com.igd.socket.sdk.ISocketServer;

public class ReactorNIOSocketServer implements ISocketServer {
	
	@Override
	public void start() throws Exception {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		Selector selector = Selector.open();
		serverSocketChannel.socket().bind(new InetSocketAddress(10022));
		serverSocketChannel.configureBlocking(false);
		//注册连接事件
		SelectionKey selectionKey =	serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		selectionKey.attach(new Acceptor(serverSocketChannel));
		
		/**
		 * 循环获取连接或读，既负责连接请求
		 */
		while(true) {
			selector.select();
			Iterator<SelectionKey> keysItr = selector.selectedKeys().iterator();
			while(keysItr.hasNext()) {
				SelectionKey sKey =	keysItr.next();
				if(sKey.isAcceptable()) {
					System.out.println("isAcceptable："  + sKey.isAcceptable() + " isConnectable：" + sKey.isConnectable() + " isReadable：" + sKey.isReadable() + " isValid：" + sKey.isValid());
					// 该步骤是同步的处理，具体的业务逻辑的快慢会影响下一个selector.select()的获取，特别是WorkHandler的业务处理，可在WorkHandler内部使用线程池
					Runnable runnable = (Runnable)sKey.attachment();
					runnable.run();
				}
				keysItr.remove();	
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		new ReactorNIOSocketServer().start();
	}

}
